import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EventBus.dart';
import 'package:flutter_enjoy_plus/utils/Toast.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Timer? _timers;
  int timerCount = 60;
  getCodeWidget() {
    if (_timers == null) {
      return const Text('获取验证码');
    } else {
      return Text('$timerCount秒后重新获取');
    }
  }

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _phoneController.text = '18777777777';
  }

  _sendCode() async {
    if (_phoneController.text.isEmpty) {
      PromptAction.showFail('请输入手机号');
      return;
    } else {
      final regExp = RegExp(r'^(?:(?:\+|00)86)?1\d{10}$');
      if (!regExp.hasMatch(_phoneController.text)) {
        PromptAction.showFail('请输入正确的手机号');
        return;
      }
    }

    if (_timers == null) {
      final res = await beginCountDown();
      _codeController.text = res;
      PromptAction.showToast('获取验证码成功');
    } else {
      return PromptAction.showToast('请稍后再试');
    }

  }

  Login() async {

    if (_phoneController.text.isEmpty) {
      PromptAction.showFail('请输入手机号');
      return;
    } else {
      final regExp = RegExp(r'^(?:(?:\+|00)86)?1\d{10}$');
      if (!regExp.hasMatch(_phoneController.text)) {
        PromptAction.showFail('请输入正确的手机号');
        return;
      }
    }

    if (_codeController.text.isEmpty) {
      PromptAction.showFail('请输入验证码');
      return;
    }
    final res = await loginAPI({
      'mobile': _phoneController.text,
      'code': _codeController.text,
    });

    // 关闭定时器
    _timers?.cancel();
    _timers = null;
    // 存TOKEN
    tokenManager.setToken(res['token'],res['refreshToken']);
    
    eventBus.fire(LoginEventBus());
    // 返回
    Navigator.pop(context);
  }

  beginCountDown() async {
    _timers = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (timerCount <= 0) {
        _timers?.cancel();
        _timers = null;
        timerCount = 60;
      }
      timerCount--;
      setState(() {});
    });
    final res = await getCodeAPI({
      'mobile': _phoneController.text,
    });
    return res['code'];
  }

@override
  void dispose() {
    _timers?.cancel();
    _timers = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _sendCode();
                  },
                  child: getCodeWidget(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      Login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
